package com.starhub.domain.annotate.util;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.starhub.application.collection.dto.DataManipulationDto;
import com.starhub.application.collection.entity.KnowledgeCollection;
import com.starhub.application.collection.service.DataManipulationService;
import com.starhub.application.collection.service.KnowledgeCollectionService;
import com.starhub.common.security.util.SecurityUtils;
import com.starhub.domain.annotate.enums.UseTypeEnums;
import com.starhub.domain.knowledge.dto.KnowledgeItemDto;
import com.starhub.domain.knowledge.service.KnowledgeService;
import com.starhub.domain.knowledge.vo.KnowledgeItemVo;
import com.starhub.engine.generator.genid.IdGenerator;
import com.starhub.utils.Util;

import lombok.extern.slf4j.Slf4j;

/**
 * 数据处理工具类
 * 
 * @version: V1.0
 * @author: liuhf
 * @time 2025-06-19
 */
@Slf4j
@Component
public class DataUtil {

    @Autowired
    private KnowledgeService knowledgeService;

    /**
     * 处理数据项列表
     * 
     * @param dataItems      数据项列表
     * @param metaCollection 元数据集合信息
     * @return 处理后的ID列表
     */
    public List<String> processDataItems(List<String> dataItems, KnowledgeCollection metaCollection) {
        List<String> resultIds = new ArrayList<>();

        for (String itemData : dataItems) {
            String itemId = processDataItem(itemData, metaCollection);
            if (!Util.isEmpty(itemId)) {
                resultIds.add(itemId);
            }
        }

        return resultIds;
    }

    /**
     * 处理单个数据项
     * 
     * @param itemData       数据内容
     * @param metaCollection 元数据集合信息
     * @return 数据项ID
     */
    private String processDataItem(String itemData, KnowledgeCollection metaCollection) {
        try {
            // 1. 检查数据是否已存在
            String existingId = checkDataExists(itemData, metaCollection);

            if (!Util.isEmpty(existingId)) {
                return existingId;
            }

            // 2. 如果使用方式为固定，则不创建新数据
            if (metaCollection.getUseType() == UseTypeEnums.FIXED.getCode()) {
                return "";
            }

            // 3. 数据不存在，创建新数据
            String newId = createNewData(itemData, metaCollection);
            log.info("Created new data with id: {} for content: {}", newId, itemData);
            return newId;

        } catch (Exception e) {
            log.error("Failed to process data item: {}", itemData, e);
            throw new RuntimeException("Failed to process data item: " + itemData, e);
        }
    }

    /**
     * 检查数据是否已存在
     * 
     * @param itemData       数据内容
     * @param metaCollection 元数据集合信息
     * @return 如果存在返回ID，否则返回null
     */
    private String checkDataExists(String itemData, KnowledgeCollection metaCollection) {
        try {
            // 直接调用KnowledgeCollectionService的方法查询数据ID
            KnowledgeItemVo existingData = knowledgeService
                    .getKnowledgeItemByContent(Util.null2String(metaCollection.getId()), itemData);

            if (existingData == null) {
                return "";
            }

            return Util.null2String(existingData.getId());
        } catch (Exception e) {
            log.error("Failed to check data existence: {}", itemData, e);
            return "";
        }
    }

    /**
     * 创建新数据
     * 
     * @param itemData       数据内容
     * @param metaCollection 元数据集合信息
     * @return 新创建数据的ID
     */
    private String createNewData(String itemData, KnowledgeCollection metaCollection) {
        try {

            String id = knowledgeService.createKnowledgeItem(KnowledgeItemDto.builder()
                    .content(itemData)
                    .collectionId(metaCollection.getId())
                    .baseId(metaCollection.getBaseId())
                    .name(itemData)
                    .title(itemData)
                    .content(itemData)
                    .creatorId(Util.getLongValue(SecurityUtils.getCurrentUserId()))
                    .build(), false);

            // 保存数据
            return id;
        } catch (Exception e) {
            log.error("Failed to create new data: {}", itemData, e);
            throw new RuntimeException("Failed to create new data: " + itemData, e);
        }
    }
}
